package com.thrd.basicframework.ui;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapRegionDecoder;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;

import androidx.annotation.Nullable;


import com.thrd.basicframework.utils.LogUtil;
import com.thrd.basicframework.utils.ToastUtil;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 超大图显示控件
 */
public class LargeImageView extends View implements GestureDetector.OnGestureListener {
    private static final String TAG = "LargeImageView";

    private Paint mPaint;

    private BitmapRegionDecoder mDecoder;

    //绘制的区域
    private volatile Rect mRect = new Rect();

    private int mScaledTouchSlop;

    // 分别记录上次滑动的坐标
    private int mLastX = 0;
    private int mLastY = 0;

    //图片的宽度和高度
    private int mImageWidth, mImageHeight;
    //手势控制器
    private GestureDetector mGestureDetector;
    private BitmapFactory.Options options;


    //间距
    private final static int mJianJuX=320;

    //  private OnTextCallback onTextCallback;

    //    private  final static int
    private int positionItem=0;
    private List<String> list;

    private int touchX;
    private int touchY;
    private int jiaoDianX=0;
    private int jiaoDianY=600;

    private OnCoordinateCallback onCoordinateCallback;
    public LargeImageView(Context context) {
        this(context,null);
    }

    public LargeImageView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    public LargeImageView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mPaint = new Paint();
        init(context,attrs);
//        Scroller mScroller = new Scroller(getContext());
//        setFocusable(true);
//        setDescendantFocusability(FOCUS_AFTER_DESCENDANTS);
//        setWillNotDraw(false);
//        final ViewConfiguration configuration = ViewConfiguration.get(context);
//        mTouchSlop = configuration.getScaledTouchSlop();
//        mMinimumVelocity = configuration.getScaledMinimumFlingVelocity();
//        mMaximumVelocity = configuration.getScaledMaximumFlingVelocity();
    }


    private void init(Context context, AttributeSet attrs) {
        //设置显示图片的参数，如果对图片质量有要求，就选择ARGB_8888模式
        options = new BitmapFactory.Options();
        options.inPreferredConfig = Bitmap.Config.ARGB_8888;


        mScaledTouchSlop = ViewConfiguration.get(getContext())
                .getScaledTouchSlop();
        LogUtil.d(TAG, "sts:" + mScaledTouchSlop);
        //初始化手势控制器
        mGestureDetector = new GestureDetector(context, this);

        //获取图片的宽高
        InputStream is = null;
        try {
            is= getClass().getResourceAsStream("/assets/time.jpg");
            String path = new String(InputStreamToByte(is ));

            is = context.getResources().getAssets().open("time.jpg");
            //初始化BitmapRegionDecode，并用它来显示图片
            mDecoder = BitmapRegionDecoder
                    .newInstance(is, false);
            BitmapFactory.Options tmpOptions = new BitmapFactory.Options();
            // 设置为true则只获取图片的宽高等信息，不加载进内存
            tmpOptions.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(path,  tmpOptions);
            mImageWidth = tmpOptions.outWidth;
            mImageHeight = tmpOptions.outHeight;
//            mImageWidth = rect.width();
//            mImageHeight = rect.height();
//            mImageWidth = 5948;
//            mImageHeight = 0;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                touchX = (int) event.getX();
                touchY = (int) event.getY();
                Log.e(TAG,"touchX="+touchX);
                break;

            case MotionEvent.ACTION_UP:
                int x = (int) event.getX();
                int y = (int) event.getY();

                if ((Math.abs(x - touchX) < 30) && (Math.abs(y - touchY) < 30)) {

//                    int itemWidth=getWidth()- jiaoDianX;
//                    int item=itemWidth/mJianJuX+1;
                    Log.e(TAG,"点的位置="+x+"坐标位置"+(jiaoDianX+(mJianJuX*2)));
                    if((Math.abs(x- jiaoDianX) < 30)&&(Math.abs(y- jiaoDianY)<30)){
                        ToastUtil.show(getContext(),"点击第一个");
                    }else
                    if((Math.abs(x- (jiaoDianX+(mJianJuX*2))) < 30)&&(Math.abs(y- jiaoDianY)<30)){
                        ToastUtil.show(getContext(),"点击第二个");
                    }else
                    if((Math.abs(x- (jiaoDianX+(mJianJuX*4))) < 30)&&(Math.abs(y- jiaoDianY)<30)){
                        ToastUtil.show(getContext(),"点击第三个");
                    }


                }
                break;


            default:
                break;
        }


        //把触摸事件交给手势控制器处理
        return mGestureDetector.onTouchEvent(event);
//        return true;
    }

    @Override
    public boolean onDown(MotionEvent e) {
        mLastX = (int) e.getRawX();
        mLastY = (int) e.getRawY();
        return true;
    }

    @Override
    public void onShowPress(MotionEvent e) {

    }

    @Override
    public boolean onSingleTapUp(MotionEvent event) {
//        // 获取离开屏幕的手指的索引
//        int pointerIndexLeave = event.getActionIndex();
//        int pointerIdLeave = event.getPointerId(pointerIndexLeave);
//        if (mPointerId == pointerIdLeave) {
//            // 离开屏幕的正是目前的有效手指，此处需要重新调整，并且需要重置VelocityTracker
//            int reIndex = pointerIndexLeave == 0 ? 1 : 0;
//            mPointerId = event.getPointerId(reIndex);
//            // 调整触摸位置，防止出现跳动
//            x = event.getX(reIndex);
//            y = event.getY(reIndex);
//            if (velocityTracker != null)
//                velocityTracker.clear();
//        }
        return false;
    }

    @Override
    public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
        int x = (int) e2.getRawX();
        int y = (int) e2.getRawY();
        move(x, y);

        return true;
    }

    /**
     * 移动的时候更新图片显示的区域
     *
     * @param x
     * @param y
     */
    private void move(int x, int y) {
        int deltaX = x - mLastX;
        int deltaY = y - mLastY;
        LogUtil.d(TAG, "move, deltaX:" + deltaX );
        //如果图片宽度大于屏幕宽度
        if (mImageWidth > getWidth()) {
            //移动rect区域
            mRect.offset(-deltaX, 0);
            //检查是否到达图片最右端
            if (mRect.right > mImageWidth) {
                mRect.right = mImageWidth;
                mRect.left = mImageWidth - getWidth();
            }

            //检查左端
            if (mRect.left < 0) {
                mRect.left = 0;
                mRect.right = getWidth();
            }

            invalidate();
        }
//        //如果图片高度大于屏幕高度
//        if (mImageHeight > getHeight()) {
//            mRect.offset(0, -deltaY);
//
//            //是否到达最底部
//            if (mRect.bottom > mImageHeight) {
//                mRect.bottom = mImageHeight;
//                mRect.top = mImageHeight - getHeight();
//            }
//
//            if (mRect.top < 0) {
//                mRect.top = 0;
//                mRect.bottom = getHeight();
//            }
//            //重绘
//            invalidate();
//        }


        mLastX = x;
        mLastY = y;
    }

    @Override
    public void onLongPress(MotionEvent e) {
        mLastX = (int) e.getRawX();
        mLastY = (int) e.getRawY();
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
        int x = (int) e2.getRawX();
        int y = (int) e2.getRawY();
        move(x, y);
        return true;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        //显示图片
        Bitmap bm = mDecoder.decodeRegion(mRect, options);
        canvas.drawBitmap(bm, 0, 0, null);
// 创建画笔


        if(mRect!=null){
            mPaint.setColor(Color.RED);// 设置红色
            int left=mRect.left;
            if(left>mJianJuX){
                int width=left-mJianJuX;        //40
                int awidth=width/(mJianJuX*2);  //0
                positionItem=awidth+1;          //获取焦点item
                jiaoDianX= (positionItem*mJianJuX*2)-width;  //0*200+30
            }else{
                positionItem=0;
                jiaoDianX=mJianJuX- left;
            }

            mPaint.setColor(Color.RED);
            canvas.drawCircle(jiaoDianX, jiaoDianY, 20, mPaint);// 大圆
            if(onCoordinateCallback!=null){
                onCoordinateCallback.onCoordinate(jiaoDianX,jiaoDianY,positionItem);
            }
            mPaint.setColor(Color.BLACK);
            canvas.drawCircle(jiaoDianX+(mJianJuX*2), jiaoDianY, 20, mPaint);// 大圆
            canvas.drawCircle(jiaoDianX+(mJianJuX*4), jiaoDianY, 20, mPaint);// 大圆
//            mPaint.setColor(Color.parseColor("#50ffffff"));
//            Path path = new Path();
//            path.moveTo(jiaoDianX-100, 200);// 此点为多边形的起点
//            path.lineTo(jiaoDianX+100, 200);
//            path.lineTo(jiaoDianX+100, 400);// 此点为多边形的起点
//            path.lineTo(jiaoDianX-100, 400);
//            path.close(); // 使这些点构成封闭的多边形
//            canvas.drawPath(path, mPaint);
//
//
//
//
//            mPaint.setColor(Color.BLACK);        // 设置颜色
//            mPaint.setStyle(Paint.Style.FILL);   // 设置样式
//            mPaint.setTextSize(30);
//            TextPaint textPaint = new TextPaint();
//            textPaint.setARGB(0xFF, 0xFF, 0, 0);
//            textPaint.setTextSize(20.0F);
//            String aboutTheGame = "关于本游戏：本游戏是做测试用的，这些文字也是，都不是瞎写的！sasasasasasasasa ";
//            StaticLayout layout = new StaticLayout(aboutTheGame,textPaint,200, Layout.Alignment.ALIGN_NORMAL,1.0F,0.0F,true);
////            can.translate(20,80);
//            canvas.save();
//            canvas.translate(jiaoDianX-100, 200);
//            layout.draw(canvas);
//                if(onTextCallback!=null){
//
//                }

//            }else{
//                int x=mJianJuX- left;
//                LogUtil.e(TAG,"x="+x);
//                canvas.drawCircle(mJianJuX- left, 600, 20, mPaint);// 大圆
//            }

        }


    }




    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        int width = getMeasuredWidth();
        int height = getMeasuredHeight();


        int imageWidth = mImageWidth;
        int imageHeight = mImageHeight;

        //默认显示图片的中心区域，开发者可自行选择
        mRect.left = 0;
        mRect.top = 0;
        mRect.right = mRect.left + width;
        mRect.bottom = mRect.top + height;

//        mRect.top = imageWidth / 2 - width / 2;
//        mRect.left = imageHeight / 2 - height / 2;
//        mRect.bottom= mRect.left + width;
//        mRect.right= mRect.top + height;

    }


    interface  OnCoordinateCallback{
        void onCoordinate(int x, int y, int positionItem);
    }



    public void setTextList(List<String> list){
        this.list=list;
    }

    public OnCoordinateCallback getOnCoordinateCallback() {
        return onCoordinateCallback;
    }

    public void setOnCoordinateCallback(OnCoordinateCallback onCoordinateCallback) {
        this.onCoordinateCallback = onCoordinateCallback;
    }


    private byte[] InputStreamToByte(InputStream is) throws IOException {
        ByteArrayOutputStream bytestream = new ByteArrayOutputStream();
        int ch;
        while ((ch = is.read()) != -1) {
            bytestream.write(ch);
        }
        byte imgdata[] = bytestream.toByteArray();
        bytestream.close();
        return imgdata;
    }




}
